<template>
  <section class="lettery-prize">
    <el-dialog v-el-drag-dialog :visible.sync="visible" :close-on-click-modal="false" title="奖品设置" center fullscreen @close="handleCancel()">
      <section class="prize-main">
        <section class="main-add" @click="handleCreate"><i class="el-icon-plus" />添加奖品</section>
        <section class="main-table">
          <el-table :data="list" style="width: 100%">
            <el-table-column type="index" width="50" />
            <el-table-column prop="prizeName" label="奖品名称" />
            <el-table-column prop="prizeImg" label="奖品图片">
              <template slot-scope="scope">
                <el-image :src="view + scope.row.prizeImg" :preview-src-list="[view + scope.row.prizeImg]">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <!-- <el-table-column v-if="drawForm === 'CJXS_JGG'" prop="winImg" label="中奖图片">
              <template slot-scope="scope">
                <el-image :src="view + scope.row.winImg" :preview-src-list="[view + scope.row.winImg]">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </template>
            </el-table-column> -->
            <el-table-column prop="prizeTypeValue" align="center" label="奖品类型" />
            <el-table-column prop="prizeCount" align="center" label="奖品份数" />
            <el-table-column align="center" label="奖品额度范围">
              <template slot-scope="scope">
                <span>{{
                  scope.row.priceOnceNumberMini == scope.row.priceOnceNumber
                    ? scope.row.priceOnceNumber
                    : scope.row.priceOnceNumberMini + '~' + scope.row.priceOnceNumber
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="winningProbability" align="center" label="中奖概率(%)" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </section>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="handleCancel()">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :visible.sync="addvisible"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      append-to-body
      title="奖品设置"
      center
      width="800px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" style="height: 520px;">
        <el-form-item label="奖品类型:" prop="prizeType">
          <el-select v-model="form.prizeType" placeholder="请选择" @change="handleTypeChange">
            <el-option v-for="(item, index) in prizepool" :key="index" :label="item.prizeName" :value="item.id" />
            <!-- <el-option v-for="(item, index) in dict.BIGTPPT" :key="index" :label="item.dictName" :value="item.dictValue" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="奖品名称" prop="prizeName">
          <el-input v-model.trim="form.prizeName" placeholder="请输入奖品名称" />
        </el-form-item>
        <!-- <el-form-item v-if="form.prizeType == 'BIGTPPT01'" label="选择福币:" prop="prizeRelationId">
          <el-select v-model="form.prizeRelationId" placeholder="请选择">
            <el-option v-for="(item, index) in coins" :key="index" :label="item.goldGiveName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.prizeType == 'BIGTPPT02'" label="选择优惠卷:" prop="prizeRelationId">
          <el-select v-model="form.prizeRelationId" placeholder="请选择">
            <el-option v-for="(item, index) in coupons" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="奖品图片" prop="prizeImg">
          <image-upload
            ref="upload"
            :key="upload.imagecropperKey"
            v-model="form.prizeImg"
            :preview-id="upload.viewId"
            :forever="true"
            :width="100"
            :view="upload.view"
            :height="100"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <!-- <el-form-item v-if="drawForm === 'CJXS_JGG'" label="中奖图片" prop="winImg">
          <image-upload
            ref="uploadWin"
            :key="uploadWin.imagecropperKey"
            v-model="form.winImg"
            :preview-id="uploadWin.viewId"
            :forever="true"
            :width="100"
            :view="uploadWin.view"
            :height="100"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item> -->
        <el-form-item label="奖品说明" prop="prizeExplain">
          <el-input v-model="form.prizeExplain" type="textarea" placeholder="请输入奖品说明" />
        </el-form-item>
        <el-form-item label="奖品份数" prop="prizeCount">
          <el-input-number v-model="form.prizeCount" :max="max" />
        </el-form-item>
        <el-form-item label="单次中奖" required>
          <el-row :gutter="10">
            <el-col :span="10">
              <el-form-item label prop="priceOnceNumberMini">
                <el-input-number v-model="form.priceOnceNumberMini" :min="1" />
              </el-form-item>
            </el-col>
            <el-col :span="2">--</el-col>
            <el-col :span="10">
              <el-form-item label prop="priceOnceNumber">
                <el-input-number v-model="form.priceOnceNumber" :min="1" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label>
          <section class="inner-explain">
            <section><i class="el-icon-warning-outline" />当单次中奖值相等时，奖品发放数量为设置的固定值。</section>
            <section><i class="el-icon-warning-outline" />当奖品类型为现金时，单位为“分”。</section>
          </section>
        </el-form-item>

        <el-form-item label="中奖概率(%)" prop="winningProbability">
          <el-input v-model="form.winningProbability" placeholder="请输入中奖概率" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" @click="addvisible = false">取 消</el-button>
        <el-button type="primary" @click="state == 'create' ? createData() : updateData()">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { specialText, int, intwith } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog'
import { getDictByCode, query, insert, update, del, get, queryCoins, queryCoupons, queryPrizePool } from './../api/prize'
import ImageUpload from '@/components/ImageUpload'
export default {
  name: 'Rushprize',
  directives: { elDragDialog },
  components: { ImageUpload },
  props: {
    id: {
      type: String,
      default: ''
    },
    drawForm: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      state: 'create',
      visible: true,
      addvisible: false,
      view: '/API-DOCUMENT/document/file/download?id=',
      max: 100000,
      form: {
        id: '',
        prizeType: '',
        prizeRelationId: '',
        prizeName: '',
        prizeExplain: '',
        prizeImg: '',
        // winImg: '',
        prizeCount: '',
        priceOnceNumberMini: '',
        priceOnceNumber: '',
        winningProbability: ''
      },
      rules: {
        prizeType: [{ required: true, message: '请选择奖品类型', trigger: 'blur' }],
        prizeRelationId: [{ required: true, message: '请关联奖品', trigger: 'blur' }],
        prizeExplain: [{ required: true, message: '请输入奖品说明', trigger: 'blur' }],
        prizeName: [
          { required: true, message: '请输入奖品名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        prizeImg: [{ required: true, message: '请上传奖品图片', trigger: 'blur' }],
        // winImg: [{ required: true, message: '请上传中奖后图片', trigger: 'blur' }],
        prizeCount: [{ required: true, message: '请输入奖品份数', trigger: 'blur' }],
        priceOnceNumber: [{ required: true, message: '请输入奖品发放数量最大值', trigger: 'blur' }],
        priceOnceNumberMini: [{ required: true, message: '请输入奖品发放数量最小值', trigger: 'blur' }],
        winningProbability: [
          { required: true, message: '请输入中奖概率', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value == 0) {
                callback(new Error('请输入正确格式数字(保留七位小数)'))
              } else {
                const reg = /^[0-9]+([.]{1}[0-9]{1,7})?$/
                if (!reg.test(value)) {
                  callback(new Error('请输入正确格式数字(保留七位小数)'))
                } else {
                  callback()
                }
              }
            },
            trigger: 'blur'
          }
        ]
      },
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      uploadWin: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      list: [],
      coins: [],
      coupons: [],
      prizepool: [],
      dict: {
        QUESTIONLEVEL: [], // 试题难度
        BIGTPPT: [] // 奖品类型
      },
      total: 0
    }
  },
  watch: {
    'form.winningProbability': {
      handler(newName, oldName) {
        if (newName > 100 - this.total) {
          this.$message({
            title: '',
            message: '总中奖概率不能大于100%',
            type: 'warning',
            duration: 1500
          })
          this.form.winningProbability = ''
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.visible = true
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getPrizePool()
    this.getList()
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    handleTypeChange(value) {
      console.log(value)
      const obj = this.prizepool.find((a) => a.id === value)
      this.form.prizeName = obj.prizeName
      this.max = obj.prizeCount
    },

    getPrizePool() {
      return new Promise((resolve, reject) => {
        queryPrizePool()
          .then(({ data }) => {
            this.prizepool = data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    getCoins() {
      return new Promise((resolve, reject) => {
        queryCoins({ status: 'GOLDPOOLSTATUS01' })
          .then(({ data }) => {
            this.coins = data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    getCoupons() {
      return new Promise((resolve, reject) => {
        queryCoupons()
          .then(({ data }) => {
            this.coupons = data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    handleCreate() {
      if (this.list.length >= 6 && this.drawForm !== 'CJXS_JGG') {
        this.$message({
          title: '',
          message: '最多添加6个奖品',
          type: 'warning',
          duration: 1500
        })
      } else if (this.drawForm === 'CJXS_JGG' && this.list.length >= 8) {
        this.$message({
          title: '',
          message: '最多添加8个奖品',
          type: 'warning',
          duration: 1500
        })
      } else {
        for (const key in this.form) {
          if (key === 'winningProbability') {
            this.form[key] = 100 - this.total < 0 ? 0 : 100 - this.total
          } else {
            this.form[key] = ''
          }
        }
        this.state = 'create'
        this.addvisible = true
        this.$nextTick(() => {
          this.$refs.upload.reset()
          this.$set(this.upload, 'viewId', '')
          // if (this.drawForm === 'CJXS_JGG') {
          //   this.$refs.uploadWin.reset()
          //   this.$set(this.uploadWin, 'viewId', '')
          // }
          this.$refs['form'].clearValidate()
        })
      }
    },

    getList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        query({ bigturntableId: this.id })
          .then(({ data }) => {
            loading.close()
            this.list = Object.assign([], data.data)
            this.total = 0
            if (this.list && this.list.length > 0) {
              this.list.forEach((item) => {
                this.total += Number(item.winningProbability)
              })
            }
          })
          .catch((error) => {
            reject(error)
            loading.close()
          })
      })
    },

    checkRatio(t, i) {
      let number = Number(this.form.winningProbability)
      if (t === 'create') {
        if (this.list.length === 5 && this.drawForm === 'CJXS_DZP') {
          this.list.forEach((a) => {
            number += Number(a.winningProbability)
          })
          if (number !== 100) {
            this.$message({
              title: '',
              message: '奖品数量为6时，中奖概率总和必须为100%',
              type: 'warning',
              duration: 2000
            })
            return false
          }
        } else if (this.list.length === 8 && this.drawForm === 'CJXS_JGG') {
          this.list.forEach((a) => {
            number += Number(a.winningProbability)
          })
          if (number !== 100) {
            this.$message({
              title: '',
              message: '奖品数量为9时，中奖概率总和必须为100%',
              type: 'warning',
              duration: 2000
            })
            return false
          }
        } else {
          return true
        }
      } else {
        if (this.list.length === 6 && this.drawForm === 'CJXS_DZP') {
          this.list.forEach((a) => {
            if (a.id !== i) {
              number += Number(a.winningProbability)
            }
          })
          if (number !== 100) {
            this.$message({
              title: '',
              message: '奖品数量为6时，奖品中奖概率总和必须为100%',
              type: 'warning',
              duration: 2000
            })
            return false
          }
        } else if (this.list.length === 9 && this.drawForm === 'CJXS_JGG') {
          this.list.forEach((a) => {
            if (a.id !== i) {
              number += Number(a.winningProbability)
            }
          })
          if (number !== 100) {
            this.$message({
              title: '',
              message: '奖品数量为9时，奖品中奖概率总和必须为100%',
              type: 'warning',
              duration: 2000
            })
            return false
          }
        } else {
          return true
        }
      }
      return true
    },

    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.checkRatio('create', '')) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['bigturntableId'] = this.id
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.addvisible = false
                  this.getList()
                })
                .catch((error) => {
                  loading.close()
                  reject(error)
                })
            })
          }
        } else {
          return false
        }
      })
    },

    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.checkRatio('update', this.form.id)) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['bigturntableId'] = this.id
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '设置成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.addvisible = false
                  this.getList()
                })
                .catch((error) => {
                  loading.close()
                  reject(error)
                })
            })
          }
        } else {
          return false
        }
      })
    },

    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(row.id)
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'prizeImg') {
                this.upload.viewId = data[key]
              }
              // if (key === 'winImg') {
              //   this.uploadWin.viewId = data[key]
              // }
              if (key === 'winningProbability') {
                this.total = this.total - Number(data[key])
              }
              this.form[key] = data[key]
            }
            this.state = 'update'
            this.addvisible = true
            this.$nextTick(() => {
              this.$refs['form'].clearValidate()
            })
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },

    handleDelete(row) {
      this.$confirm('确定删除该奖品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            del(row.id)
              .then(() => {
                loading.close()
                this.$message({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              })
              .catch((error) => {
                loading.close()
                reject(error)
              })
          })
        })
        .catch()
    },

    handleCancel() {
      this.$emit('cancel')
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';
.lettery-prize {
  .prize-main {
    min-height: calc(100vh - 140px);
    max-height: calc(100vh - 140px);
    overflow: hidden;
    position: relative;
    .main-add {
      width: 100%;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border: 1px dotted #d9d9d9;
      border-radius: 4px;
      color: rgba(0, 0, 0, 0.85);
      cursor: pointer;
      &:hover {
        @include font-color($mainColor);
        @include border-color(1px, dotted, $mainColor);
      }
    }
    .main-table {
      position: absolute;
      top: 50px;
      left: 0;
      right: 0;
      bottom: 0;
      box-sizing: border-box;
      overflow: hidden;
      &::-webkit-scrollbar {
        width: 8px; /*对垂直流动条有效*/
        height: 1px; /*对水平流动条有效*/
      }
      /** 滚动条轨道*/
      &::-webkit-scrollbar-track {
        box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
        background-color: white;
        border-radius: 3px;
      }
      /** 滚动条里面小方块*/
      &::-webkit-scrollbar-thumb {
        height: 32px;
        border-radius: 5px;
        box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
        background-color: #eaeaea;
      }
      &:hover {
        overflow: auto;
      }
      .el-image {
        width: 50px;
        height: 50px;
      }
    }
  }
  .inner-explain {
    margin-top: 10px;
    line-height: 1.1;
    color: #999;
    font-size: 14px;
    display: flex;
    align-items: flex-start;
    > i {
      margin-right: 5px;
    }

    p {
      margin: 0;
      padding: 0;
      margin-bottom: 5px;
    }
  }
}
</style>
